<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item label="排班日期" prop="searchDateRange">
        <el-date-picker clearable size="small" @change="handleQuery"
                        v-model="queryParams.searchDateRange"
                        type="daterange"
                        value-format="yyyy-MM-dd"
                        range-separator="至"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="班次" prop="classesId">
        <el-select v-model="queryParams.classesId" placeholder="请选择班次" clearable size="small" @change="handleQuery">
          <el-option
            v-for="classes in classesList"
            :key="classes.classesId"
            :label="classes.classesName"
            :value="classes.classesId"/>
        </el-select>
      </el-form-item>
      <el-form-item label="班组" prop="teamId">
        <el-select v-model="queryParams.teamId" placeholder="请选择班组" clearable size="small" @change="handleQuery">
          <el-option
            v-for="team in teamList"
            :key="team.teamId"
            :label="team.teamName"
            :value="team.teamId"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['group:sche:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['group:sche:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['group:sche:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="mini"
          @click="handleBatchDay"
          v-hasPermi="['group:sche:add']"
        >全天批量排班
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="mini"
          @click="handleAutoSche"
          v-hasPermi="['group:sche:add']"
        >自动排班设置
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="scheList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="排班日期" align="center" prop="scheDate"/>
      <el-table-column label="班次" align="center" prop="classes.classesName"/>
      <el-table-column label="班组" align="center" prop="team.teamName"/>
      <el-table-column label="开始时间" align="center" prop="startDt"/>
      <el-table-column label="结束时间" align="center" prop="endDt"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['group:sche:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['group:sche:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改排班计划对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="排班日期" prop="scheDate">
          <el-date-picker clearable size="small" style="width: 200px"
                          v-model="form.scheDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择排班日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="班次" prop="classesId">
          <el-select v-model="form.classesId" placeholder="请选择班次">
            <el-option
              v-for="classes in classesList"
              :key="classes.classesId"
              :label="classes.classesName"
              :value="classes.classesId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="班组" prop="teamId">
          <el-select v-model="form.teamId" placeholder="请选择班组">
            <el-option
              v-for="team in teamList"
              :key="team.teamId"
              :label="team.teamName"
              :value="team.teamId"/>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="全天排班" :visible.sync="openBatchDay" width="500px" append-to-body>
      <el-form ref="batchDayForm" :model="batchDayForm" :rules="rules" label-width="150px">
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker clearable size="small" style="width: 200px"
                          v-model="batchDayForm.startDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker clearable size="small" style="width: 200px"
                          v-model="batchDayForm.endDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择结束日期">
          </el-date-picker>
        </el-form-item>
        <table class="table">
          <thead>
          <tr>
            <th>班次</th>
            <th>班组</th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="row in batchDayForm.scheList">
            <td>{{row.classesName}}</td>
            <td class="input">
              <el-select v-model="row.teamId" placeholder="请选择班组" style="width: 100%">
                <el-option
                  v-for="team in teamList"
                  :key="team.teamId"
                  :label="team.teamName"
                  :value="team.teamId"/>
              </el-select>
            </td>
          </tr>
          </tbody>
        </table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormBatchDay">确 定</el-button>
        <el-button @click="cancelBatchDay">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="自动排班" :visible.sync="autoScheDialog.open" width="500px" append-to-body>
      <el-form ref="autoScheForm" :model="autoScheDialog.form" :rules="autoScheDialog.rules" label-width="150px">
        <el-form-item label="初始日期" prop="initDate">
          <el-date-picker clearable size="small" style="width: 200px"
                          v-model="autoScheDialog.form.initDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="初始班次" prop="classesId">
          <el-select v-model="autoScheDialog.form.classesId" placeholder="请选择班次">
            <el-option
              v-for="classes in classesList"
              :key="classes.classesId"
              :label="classes.classesName"
              :value="classes.classesId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="初始班组" prop="teamId">
          <el-select v-model="autoScheDialog.form.teamId" placeholder="请选择班组">
            <el-option
              v-for="team in teamList"
              :key="team.teamId"
              :label="team.teamName"
              :value="team.teamId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="自动排班启用" prop="autoScheEnable">
          <el-switch v-model="autoScheDialog.form.autoScheEnable" :active-value="1" :inactive-value="0"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormAutoSche">确 定</el-button>
        <el-button @click="autoScheDialog.open=false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  pageSche,
  getSche,
  delSche,
  addSche,
  updateSche,
  batchDaySche,
  setAutoSche,
  getAutoSche
} from '@/api/app/group/sche'
import {listClasses} from '@/api/app/group/classes'
import {listTeam} from '@/api/app/group/team'

export default {
  name: 'Sche',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 排班计划表格数据
      scheList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        searchDateRange: [this.moment().add(-7, 'd').format('YYYY-MM-DD'), this.moment().format('YYYY-MM-DD')],
        classesId: undefined,
        teamId: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        scheDate: [
          {required: true, message: '排班日期不能为空', trigger: 'blur'}
        ],
        classesId: [
          {required: true, message: '班次不能为空', trigger: 'change'}
        ],
        teamId: [
          {required: true, message: '班组不能为空', trigger: 'change'}
        ],
        startDate: [
          {required: true, message: '日期不能为空', trigger: 'blur'}
        ],
        endDate: [
          {required: true, message: '日期不能为空', trigger: 'blur'}
        ]
      },
      classesList: [],
      teamList: [],
      openBatchDay: false,
      batchDayForm: {},
      autoScheDialog: {
        open: false,
        form: {},
        rules: {
          initDate: [
            {required: true, message: '日期不能为空', trigger: 'blur'}
          ],
          classesId: [
            {required: true, message: '班次不能为空', trigger: 'change'}
          ],
          teamId: [
            {required: true, message: '班组不能为空', trigger: 'change'}
          ],
        }
      }
    }
  },
  created() {
    this.getClassesList()
    this.getTeamList()
    this.getList()
  },
  methods: {
    getClassesList() {
      listClasses({}).then(response => {
        this.classesList = response.data.rows
      })
    },
    getTeamList() {
      listTeam({}).then(response => {
        this.teamList = response.data.rows
      })
    },
    /** 查询排班计划列表 */
    getList() {
      this.loading = true
      let queryParams = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        classesId: this.queryParams.classesId,
        teamId: this.queryParams.teamId
      }
      if (this.queryParams.searchDateRange) {
        queryParams.searchStartDate = this.queryParams.searchDateRange[0]
        queryParams.searchEndDate = this.queryParams.searchDateRange[1]
      }
      pageSche(queryParams).then(response => {
        this.scheList = response.data.rows
        this.total = response.data.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        scheId: undefined,
        scheDate: undefined,
        classesId: undefined,
        teamId: undefined,
        startDt: undefined,
        endDt: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.scheId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加排班计划'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const scheId = row.scheId || this.ids
      getSche(scheId).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改排班计划'
      })
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.scheId != undefined) {
            updateSche(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          } else {
            addSche(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess('新增成功')
                this.open = false
                this.getList()
              } else {
                this.msgError(response.msg)
              }
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const scheIds = row.scheId || this.ids
      this.$confirm('是否确认删除排班计划?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        return delSche(scheIds)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(function () {
      })
    },
    handleBatchDay() {
      this.batchDayForm = {
        scheList: []
      }
      for (let i = 0; i < this.classesList.length; i++) {
        this.batchDayForm.scheList.push({
          classesId: this.classesList[i].classesId,
          classesName: this.classesList[i].classesName,
          teamId: (this.teamList[i]) ? this.teamList[i].teamId : undefined
        })
      }

      this.resetForm('batchDayForm')
      this.openBatchDay = true
    },
    submitFormBatchDay() {
      this.$refs['batchDayForm'].validate(valid => {
        if (valid) {
          batchDaySche(this.batchDayForm).then(response => {
            if (response.code === 200) {
              this.msgSuccess('新增成功')
              this.openBatchDay = false
              this.getList()
            } else {
              this.msgError(response.msg)
            }
          })
        }
      })
    },
    cancelBatchDay() {
      this.openBatchDay = false
    },
    handleAutoSche() {
      getAutoSche().then(res => {
        this.autoScheDialog.form = res.data
        this.autoScheDialog.open = true
      })
    },
    submitFormAutoSche() {
      setAutoSche(this.autoScheDialog.form).then(res => {
        this.msgSuccess('设置成功')
        this.autoScheDialog.open = false
      })
    }
  }
}
</script>
<style scoped>
.table {
  table-layout: fixed;
  border-collapse: collapse;
  width: 100%;
  text-align: center;
}

.table th, .table td {
  border: 1px solid #cccccc;
  padding: 10px;
}

.table td.input {
  padding: 0;
}
</style>
